package com.service;

import com.dao.MaterialFeatureDao;
import com.entity.MaterialFeature;
import com.util.excelUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.*;

public class MaterialFeatureOperator {

    public static final HashMap<Integer, String> pic_type = new HashMap<Integer, String>();
    public static String save_dir_path = "D:\\temp_data";

    static {
        pic_type.put(6, "XDR");
        pic_type.put(7, "SEM");
        pic_type.put(8, "TEM");
        pic_type.put(9, "BIO");
    }

    public void Analysis_material_feature_table(String source_dir_path, String source_file) {
        InputStream in = null;
        try {
            in = new FileInputStream(new File(source_dir_path + "\\" + source_file));
            XSSFWorkbook wb = new XSSFWorkbook(in);
            XSSFSheet sheet = wb.getSheetAt(0);
            //获取文件中的所有 <图片位置，图片内容>
            Map<String, PictureData> index_pic = excelUtil.getSheetPictures(sheet);
            //遍历所有行 与 列
            int r = 0;
            for (Iterator<Row> it = sheet.rowIterator(); it.hasNext(); r++) {
                //skip header
                if (r == 0 && it.hasNext()) {
                    it.next();
                    r += 1;
                }
                //收集每一行内容
                ArrayList<String> row_info = this.rowHandle(it, r, index_pic, source_file);
                //构建对象 进行处理
                MaterialFeature materialFeature = new MaterialFeature();
                materialFeature.setMaterial_Feature_Information(row_info);
                //static 方法进行数据库存储
                MaterialFeatureDao.data_save(materialFeature);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return;
    }

    private String savePicture(int row, int col, Map<String, PictureData> index_pic, String serialID) {
        //判断 <row, col>位置上有没有图片
        String row_col = new String(row + "_" + col);
        if (index_pic.containsKey(row_col)) {
            //图片内容 后缀
            PictureData pic = index_pic.get(row_col);
            String ext = pic.suggestFileExtension();
            //文件存储目录
            String dir_path_with_ts = save_dir_path + "\\" + serialID;
            //文件存储路径
            String final_path = dir_path_with_ts + "\\" + pic_type.get(col) + "." + ext;

            //文件流写入
            byte[] data = pic.getData();
            FileOutputStream out = null;
            try {
                //确认目录是已经否存在
                File file = new File(dir_path_with_ts);
                if (!file.exists())
                    file.mkdirs();

                out = new FileOutputStream(new File(final_path));
                out.write(data);
                out.close();

                return final_path;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    private ArrayList<String> rowHandle(Iterator<Row> it, int rIndex, Map<String, PictureData> index_pic, String source_file) {
        //处理每一行的内容 记录到row_info当中
        ArrayList<String> row_info = new ArrayList<>();
        XSSFRow row = (XSSFRow) it.next();

        //时间信息 、时间戳、 serialID
        Date now = new Date();
        String timeStamp = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String serialID = timeStamp + row.hashCode();

        int c = 0;
        //遍历每一cell 获取表格 String 内容
        for (Iterator<Cell> cells = row.cellIterator(); cells.hasNext(); c++) {
            XSSFCell cell = (XSSFCell) cells.next();
            cell.setCellType(CellType.STRING);
            if (c == 0)
                row_info.add(serialID);
            else if (c == 1) {
                row_info.add(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now));
            } else
                row_info.add(cell.getStringCellValue());
        }
        //按照模板 6，7，8，9列为 图片内容
        row_info.add(savePicture(rIndex, 6, index_pic, serialID));//XDR
        row_info.add(savePicture(rIndex, 7, index_pic, serialID));//SEM
        row_info.add(savePicture(rIndex, 8, index_pic, serialID));//TEM
        row_info.add(savePicture(rIndex, 9, index_pic, serialID));//BIO

        //记录 源文件
        row_info.add(source_file);

        return row_info;
    }

    @Test
    public void test_table_saving() {
        Analysis_material_feature_table("C:\\Users\\TU\\Documents\\WeChat Files\\wxid_9831548315612\\FileStorage\\File\\2020-12", "课题二 材料制备与表征数据表格-20201208.xlsx");
    }
}
